package com.monkey.demolist.greendao.base;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.monkey.demolist.R;
import com.monkey.demolist.greendao.StudentMsgBean;
import com.monkey.demolist.greendao.StudentMsgBeanDao;
import com.monkey.demolist.greendao.n.DaoMaster;
import com.monkey.demolist.greendao.n.DaoSession;
import com.monkey.demolist.greendao.n.OneVNActivity;
import com.monkey.demolist.greendao.one.OneVOneActivity;

import org.greenrobot.greendao.query.Query;
import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

/**
 * Description: GreenDao基本增删改查
 * Author: Arthor
 * Date: 2017/10/23
 * Time: 13:45
 */

public class BaseDaoActivity extends AppCompatActivity {

    private DaoSession daoSession;
    private StudentMsgBeanDao dao;
    private TextView result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base_dao);

        result = (TextView) findViewById(R.id.tv);
    }

    public void click(View view) {
        switch (view.getId()) {
            case R.id.init:
                init();
                break;
            case R.id.insert:
                insert();
                break;
            case R.id.delete:
                delete();
                break;
            case R.id.update:
                update();
                break;
            case R.id.query:
                query();
                break;
            case R.id.queryThread:
                queryThread();
                break;
            case R.id.onevone:
                Intent onevone = new Intent(BaseDaoActivity.this, OneVOneActivity.class);
                startActivity(onevone);
                break;
            case R.id.onevn:
                Intent onevn = new Intent(BaseDaoActivity.this, OneVNActivity.class);
                startActivity(onevn);
                break;
        }
    }

    /**
     * 初始化
     */
    private void init() {
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(getApplicationContext(), "studnet.db", null);
        SQLiteDatabase db = devOpenHelper.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(db);

        daoSession = daoMaster.newSession();
        dao = daoSession.getStudentMsgBeanDao();

        //打印SQL语句
        QueryBuilder.LOG_SQL = true;
        QueryBuilder.LOG_VALUES = true;

        query();
    }


    /**
     * 插入数据
     */
    private void insert() {

        StudentMsgBean studentMsgBean = new StudentMsgBean();
        studentMsgBean.setStudentNum("0002");
        studentMsgBean.setName("赵231份饭");
        dao.insert(studentMsgBean);
        query();
    }

    /**
     * 删除数据
     */
    private void delete() {
        List<StudentMsgBean> list = dao.queryBuilder().build().list();
        for (int i = 0; i < list.size(); i++) {
            if (i == 0) {
                dao.deleteByKey(list.get(0).getId());//通过 Id 来删除数据
//                dao.delete(list.get(0));//通过传入实体类的实例来删除数据
            }
        }
        query();
    }

    /**
     * 更新数据
     */
    private void update() {
        List<StudentMsgBean> list = dao.queryBuilder().build().list();
        for (int i = 0; i < list.size(); i++) {
            if (i == 0) {
                list.get(0).setName("钱钱钱");
                dao.update(list.get(0));
            }
        }
        query();
    }

    /**
     * 查询数据
     */
    private void query() {

        // 所有实体会直接加载到内存中
        List<StudentMsgBean> list = dao.queryBuilder().build().list();

        // 当你需要使用时，才会加载，会自动缓存。使用完必须关闭
//        LazyList<StudentMsgBean> list = dao.queryBuilder().build().listLazy();
//        list.close();

        // 如你所见，就是不会缓存的意思。使用完必须关闭。
//        LazyList<StudentMsgBean> list = dao.queryBuilder().build().listLazyUncached();
//        list.close();

        // 通过迭代器遍历结果集，不会缓存。使用完必须关闭。
//        Iterator list = dao.queryBuilder().build().listIterator();
//        while (list.hasNext()){
//            StudentMsgBean next = (StudentMsgBean) list.next();
//            Log.e("TAG", "query:" + next);
//        }

        /**
         * 条件查询
         * eq、notEq
         * like
         * between、gt、lt、ge(大于等于)、le(小于等于)
         * isNotNull isNull
         */

        // eq
//        StudentMsgBean unique = dao.queryBuilder()
//                .where(StudentMsgBeanDao.Properties.Name.eq("王"))
//                .unique();

        // like
//        list = dao.queryBuilder()
//                .where(StudentMsgBeanDao.Properties.Name.like("赵%"))
//                .list();
        //between
//        list = dao.queryBuilder()
//                .where(StudentMsgBeanDao.Properties.Id.between(11,12))
//                .list();

        // gt
//        list = dao.queryBuilder()
//                .where(StudentMsgBeanDao.Properties.Id.gt(12))
//                .list();
        // lt
//        list = dao.queryBuilder()
//                .where(StudentMsgBeanDao.Properties.Id.lt(12))
//                .list();

        /**
         * 排序
         * orderDesc 降序
         * orderAsc  升序
         */
//        list = dao.queryBuilder()
//                .orderDesc(StudentMsgBeanDao.Properties.Id)
//                .list();

        /**
         * 原生查询
         */
//        list = dao.queryBuilder()
//                .where(new WhereCondition.StringCondition("_id IN"+"(SELECT _id FROM STUDENT_MSG_BEAN WHERE _id > 12)"))
//                .list();

        /**
         * offset 偏移量
         * limit 限制
         */
//        List<StudentMsgBean> list = dao.queryBuilder()
//                .offset(0)//偏移量,相当于SQL语句中的skip
//                .limit(30)//只获取结果集的前 3 个数据
//                .orderAsc(StudentMsgBeanDao.Properties.StudentNum)//通过 StudentNum 这个属性进行正序排序
//                .where(StudentMsgBeanDao.Properties.Name.eq("赵"))//数据筛选，只获取 Name = "zone" 的数据
//                .build()
//                .list();

        result.setText(list.toString());
    }

    /**
     * 多线程查询
     */
    private void queryThread() {
        final Query<StudentMsgBean> query = dao.queryBuilder().build();

        new Thread(new Runnable() {
            @Override
            public void run() {

                // 直接查询会报错
                // DaoException: Method may be called only in owner thread, use forCurrentThread to get an instance for this thread
//                List<StudentMsgBean> list = query.list();
                List<StudentMsgBean> list = query.forCurrentThread().list();
            }
        }).start();
    }

}
